package com.xkl.springdoc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.xkl.springdoc.common.R;
import com.xkl.springdoc.domain.Role;
import com.xkl.springdoc.request.RoleDTO;
import com.xkl.springdoc.response.RoleVo;
import com.xkl.springdoc.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色管理
 *
 * @version: 1.0.0-SNAPSHOT
 * @author: 码农小卡拉
 * @createTime: 2025-09-17 11:22
 **/
@Slf4j
@Service
public class RoleServiceImpl implements IRoleService {

    private static List<Role> roleList = new ArrayList<Role>();

    @Override
    public R addRole(RoleDTO roleDTO) {
        log.info("新增角色: {}", roleDTO);
        boolean exists = roleList.stream().anyMatch(role -> role.getId().equals(roleDTO.getId()));
        if (exists) {
            log.error("角色已存在");
            return R.fail("角色已存在");
        }
        Role role = new Role();
        BeanUtil.copyProperties(roleDTO, role);
        role.setCreateTime(DateUtil.date());
        roleList.add(role);
        return R.ok();
    }

    @Override
    public R updateRole(RoleDTO roleDTO) {
        log.info("更新角色: {}", roleDTO);
        boolean exists = roleList.stream().anyMatch(role -> role.getId().equals(roleDTO.getId()));
        if (exists) {
            log.error("角色不存在");
            return R.fail("角色不存在");
        }
        roleList.stream().filter(v -> v.getId().equals(roleDTO.getId())).findFirst().ifPresent(Role -> BeanUtil.copyProperties(roleDTO, Role, CopyOptions.create().setIgnoreNullValue(true)));
        return R.ok();
    }

    @Override
    public R deleteRole(Long id) {
        return R.ok(roleList.removeIf(Role -> Role.getId().equals(id)));
    }

    @Override
    public R getRole(Long id) {
        Role Role = roleList.stream().filter(v -> v.getId().equals(id)).findFirst().orElse(null);
        if (null == Role) {
            log.error("角色不存在");
            return R.fail("角色不存在");
        }
        RoleVo vo = new RoleVo();
        BeanUtil.copyProperties(Role, vo);
        return R.ok(vo);
    }

    @Override
    public R<List<RoleVo>> getRoles() {
        List<RoleVo> list = roleList.stream().map(Role -> {
            RoleVo vo = new RoleVo();
            BeanUtil.copyProperties(Role, vo);
            return vo;
        }).toList();
        return R.ok(list);
    }
}
